package com.bjtu.literatureclient.shiro;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
	private final static Logger logger = LoggerFactory.getLogger(MyFormAuthenticationFilter.class);
	
	private final static String[] teamMembers = {"3", "4", "5", "6"};
	private final static String[] teamAdmins = {"0", "1", "2"};

	@Override
	protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
		logger.debug("issueSuccessRedirect");
		WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		boolean accessAllowed = super.isAccessAllowed(request, response, mappedValue);
		if (!accessAllowed) {
			// 判断请求是否是options请求
			String method = WebUtils.toHttp(request).getMethod();
			if (StringUtils.equalsIgnoreCase("OPTIONS", method)) {
				return true;
			}
		}
		return accessAllowed;
	}

	/**
	 * 解决未登录302问题
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		logger.info("302");
		if (isLoginRequest(request, response)) {
			if (isLoginSubmission(request, response)) {
				return executeLogin(request, response);
			} else {
				return true;
			}
		} else {
			return false;
		}

		/*
		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {
		// 使用response响应流返回数据到前台（因前端需要接受json数据，注意前后端跨域问题）
			return false;
		} else {
			return true;
		}
		 */
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {

		logger.debug("onLoginSuccess -> ");
		return true;
		//return super.onLoginSuccess(token, subject, request, response);

		//return super.onLoginSuccess(token,subject,request,response);

		/*
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (user != null) {
			HttpServletRequest req = (HttpServletRequest) request;
			String clientType = (String) req.getParameter("clienttype");
			logger.debug("[LOGIN]login success(user:" + user.getUserName() + ", client:" + clientType + ")");
			if ("pc".equals(clientType)) { // 请求方为pc，执行原方法
				return super.onLoginSuccess(token, subject, request, response);
			} else {
				logger.info("跳转逻辑");
				WebUtils.getAndClearSavedRequest(request); // 清除登录前请求路径
				
				String fallbackUrl = "/index.html";
				String role = user.getUserRole();
				
				if (user.getUserState().equals("1")) {
					// 若为第一次登陆
					if (Arrays.asList(teamAdmins).contains(role)) {
						// 若为管理员
						fallbackUrl = "/admin/memberAdd.html";
					}else if (Arrays.asList(teamMembers).contains(role)) {
						// 若为团员
						fallbackUrl = "/miuser/profile2.html";
					}
				}else if(user.getUserState().equals("2")){
					if (Arrays.asList(teamAdmins).contains(role)) {
						// 若为管理员
						fallbackUrl = "/admin/admin.html";
					}else if (Arrays.asList(teamMembers).contains(role)) {
						// 若为团员
						fallbackUrl = "/miuser/indeAdmin.html";
					}
				}
				WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
			}
		}
		return false;


		 */

		/*
		 * if (!StringUtils.isEmpty(getSuccessUrl())) { //
		 * getSession(false)：如果当前session为null,则返回null,而不是创建一个新的session Session
		 * session = subject.getSession(false); if (session != null) {
		 * session.removeAttribute("shiroSavedRequest"); } } return
		 * super.onLoginSuccess(token, subject, request, response);
		 */
	}
}
